package com.dehui.traders.ui.optioanl.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dehui.traders.R;
import com.dehui.traders.bean.OptionalCode;
import com.dehui.traders.bean.OptionalCodeRank;
import com.dehui.traders.bean.OptionalStockBean;
import com.dehui.traders.bean.SearchCodeResult;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.widgets.BaseViewHolder;
import com.dehui.traders.widgets.CommonAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

/**
 * Created by hqq on 18.4.18.
 */

public class OptionalStockAdapter extends CommonAdapter<SearchCodeResult>{

    private OnOptionalStockAdapterListener listener;

    public OptionalStockAdapter(Context context, List<SearchCodeResult> mDatas, int itemLayoutId) {
        super(context, mDatas, itemLayoutId);
    }

    public void setListener(OnOptionalStockAdapterListener listener){
        this.listener = listener;
    }

    @Override
    public void convert(BaseViewHolder helper, SearchCodeResult item, int position) {
        TextView tvName = helper.getView(R.id.tv_name);
        TextView tvCode = helper.getView(R.id.tv_code);
        ImageView ivAdd = helper.getView(R.id.iv_add);
        TextView tvAdd = helper.getView(R.id.tv_add);

        tvName.setText(item.name);
        tvCode.setText(item.code);

        boolean isAdd = false;
        String myOpitonCode = Preferences.getMyOpitonCode();
        if (!TextUtils.isEmpty(myOpitonCode)){
            List<OptionalCodeRank> codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
            for (int i = 0; i < codeList.size(); i++){
                OptionalCodeRank codeRank = codeList.get(i);
                if (codeRank.code.equals(item.code)){
                    isAdd = true;
                }
            }

        }
        ivAdd.setVisibility(isAdd ? View.GONE : View.VISIBLE);
        tvAdd.setVisibility(isAdd ? View.VISIBLE : View.GONE);

        ivAdd.setOnClickListener(v -> {
            if (listener != null)
                listener.addStock(item);
        });

    }

    public interface OnOptionalStockAdapterListener{
        void addStock(SearchCodeResult item);
    }

}
